import React, { useState, useEffect } from "react";

// 接口
interface ListItem {
  title: string;
  done: boolean;
}
type InputEvent = React.ChangeEvent<HTMLInputElement>;

const App: React.FC = function () {
  const [title, setTitle] = useState<string>("");
  const [list, setList] = useState<ListItem[]>([
    { title: "吃饭", done: false },
    { title: "睡觉", done: true },
    { title: "玩游戏", done: false },
  ]);
  const [allChecked, setAllChecked] = useState(false);
  const activeListLength = list.filter((item) => item.done).length;

  // 添加任务
  function handleAdd(): void {
    const newList = [...list, { title, done: false }];
    setList(newList);
    setTitle("");
  }
  // 选中单个任务
  function handleCheck(e: InputEvent, index: number) {
    const newList = [...list];
    newList[index].done = e.target.checked;
    setList(newList);
  }
  // 删除任务
  function handleDelete(index: number) {
    const newList = [...list];
    // let newList = list; // 会修改引用，页面不会更新
    newList.splice(index, 1);
    setList(newList);
  }
  // 全选
  function handleAllCheck(e: InputEvent) {
    const newList = [...list];
    newList.forEach((item) => (item.done = e.target.checked));
    setList(newList);
    setAllChecked(e.target.checked);
  }
  // 清理所有已完成的任务
  function handleClear() {
    setList(list.filter((item) => !item.done));
  }

  useEffect(() => {
    setAllChecked(list.length === activeListLength);
  }, [list]);
  return (
    <div style={{ margin: "20px" }}>
      <p>
        <input
          type="text"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder="请输入要添加的任务"
        />
        <button onClick={handleAdd}>添加</button>
      </p>
      {list.length ? (
        <ul>
          {list.map((item, index) => (
            <li key={index}>
              <input
                type="checkbox"
                checked={item.done}
                onChange={(e) => handleCheck(e, index)}
              />
              <span style={{ margin: "0 10px" }}>{item.title}</span>
              <button onClick={() => handleDelete(index)}>×</button>
            </li>
          ))}
        </ul>
      ) : (
        <p style={{ color: "red" }}>暂无数据</p>
      )}

      <p>
        <input
          type="checkbox"
          checked={allChecked}
          onChange={(e) => handleAllCheck(e)}
        />
        全选
        <span style={{ margin: "0 10px" }}>
          {activeListLength} / {list.length}
        </span>
        <button
          disabled={list.filter((item) => !item.done).length === list.length}
          onClick={handleClear}
        >
          clear
        </button>
      </p>
    </div>
  );
};

export default App;
